package com.ruoyi.core.config.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.JsonObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.WxUser;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.config.utils.WxUtil;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.bo.UserBo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.Date;

/**
 * @作者：xie
 * @时间：2022/8/27 10:22
 */
@RestController
@RequestMapping("core/wx")
@AllArgsConstructor
public class wxMaLoginController extends BaseController {

    private final IUserService iUserService;
    /**
     * 登陆接口
     */
    @Anonymous //放行接口
    @GetMapping("/login")
    public R<LoginVo> login( @NotBlank(message = "appid不为空") String appid, @NotBlank(message ="code不为空") String code)  {

        //通过缓存判断用户信息
            UserVo userVo = WxUtil.getUserVoByToken();
            if(ObjectUtil.isNotNull(userVo)){
            WxUtil.refreshWxUser(userVo,false);
            return WxUtil.authMsg(userVo);
        }
        //根据appid和code获取session
        WxMaJscode2SessionResult session = getSession(appid,code);
        String openid = session.getOpenid();
        //根据openid查询用户信息
        userVo=iUserService.getByOpenid(openid);
        if(ObjectUtil.isNull(userVo)){
            //无用户信息保存到数据库
            userVo = iUserService.setWxUser("",openid,"1","","");
            WxUtil.refreshWxUser(userVo,true);
            return R.fail("首次未授权",new LoginVo(StpUtil.getTokenValue(),userVo,"1"));
        }
        //有用户信息直接登录
        WxUtil.refreshWxUser(userVo,true);
        return WxUtil.authMsg(userVo);
    }

    private WxMaJscode2SessionResult getSession(String appid,String code){
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
             return wxService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            System.out.println(e.getMessage());
            throw new ServiceException("微信接口异常");
        }
    }

    @PostMapping("auth")
    public R<Void> auth(@RequestBody UserBo bo){
        if(StringUtils.isBlank(bo.getNickname())||StringUtils.isBlank(bo.getAvatar())){
            return R.fail("参数不全");
        }

            Long userId=getUserId();
            UserVo userVo = iUserService.queryById(userId);
            if(ObjectUtil.isNull(userVo)){
                return R.fail("授权有误");
            }
            UserBo userBo = BeanUtil.toBean(userVo, UserBo.class);
            userBo.setNickname(bo.getNickname());
            userBo.setAvatar(bo.getAvatar());
            iUserService.updateByBo(userBo);
            WxUtil.refreshWxUser(BeanUtil.toBean(userBo,UserVo.class),false);
            return R.ok("授权成功");

    }
}
